package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param employee
     * @param httpSession
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession httpSession){

        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername,employee.getUsername());
        Employee one = employeeService.getOne(qw);//where username = ?
        if(one == null){
            return R.error("用户名不存在");
        }
        String rawPwd = employee.getPassword();//123456
        String dbPwd = one.getPassword();//7ifausodfuojoqu87r843urieuio
        String pwd = DigestUtils.md5DigestAsHex(rawPwd.getBytes());//123456 --> fsdjfoiqwlkfj89poasjdfkj
        if(!dbPwd.equals(pwd)){
            return R.error("密码错误");
        }
        Integer status = one.getStatus();
        if(status==0){
            return R.error("员工已禁用");
        }
        httpSession.setAttribute("loginEmployee",one);
        one.setPassword(null);//
        return R.success(one);//
    }


    @PostMapping
    public R addEmployee(@RequestBody Employee employee,HttpSession httpSession){
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        boolean save = employeeService.save(employee);
        return save?R.success("添加成功"):R.error("添加失败");
    }

}
